package com.nageoffer.jobtrain.projects.mq.consumer;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.nageoffer.jobtrain.common.framework.idempotent.NoMQDuplicateConsume;
import com.nageoffer.jobtrain.common.rocketmq.base.MessageWrapper;
import com.nageoffer.jobtrain.projects.common.constant.RocketMQContent;
import com.nageoffer.jobtrain.projects.mq.event.ContestRemindDelayEvent;
import com.nageoffer.jobtrain.projects.service.handler.remind.ContestRemindExecutor;
import com.nageoffer.jobtrain.projects.service.handler.remind.dto.ContestRemindDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * 预约竞赛即将开始提醒用户
 */
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(
        topic = RocketMQContent.USER_CONTEST_REMIND_TOPIC_KEY,
        consumerGroup = RocketMQContent.USER_CONTEST_REMIND_CG_KEY
)
@Slf4j(topic = "ContestRemindDelayConsumer")
public class ContestRemindDelayConsumer implements RocketMQListener<MessageWrapper<ContestRemindDelayEvent>> {
    private final ContestRemindExecutor ContestRemindExecutor;

    // 设置三分钟的幂等标识
    @NoMQDuplicateConsume(
            keyPrefix = "contest-redeem:idempotent:",
            key = "#messageWrapper.keys",
            keyTimeout = 180
    )
    @Override
    public void onMessage(MessageWrapper<ContestRemindDelayEvent> messageWrapper) {
        // 开头打印日志，平常可 Debug 看任务参数，线上可报平安（比如消息是否消费，重新投递时获取参数等）
        log.info("[消费者] 提醒用户竞赛即将开始 - 执行消费逻辑，消息体：{}", JSON.toJSONString(messageWrapper));

        ContestRemindDelayEvent event = messageWrapper.getMessage();
        ContestRemindDTO contestRemindDTO = BeanUtil.toBean(event, ContestRemindDTO.class);

        // 将用户预约竞赛的提醒根据不同类型交给线程池进行处理
        ContestRemindExecutor.executeRemindCouponTemplate(contestRemindDTO);
    }
}